package com.tevintao.marketingsystem.xposted;

import android.os.RemoteException;
import android.text.TextUtils;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.MockServices;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;


public class WXDeviceManager {
    private static WXDeviceManager ourInstance = new WXDeviceManager();

    public static WXDeviceManager getInstance() {
        return ourInstance;
    }

    private WXDeviceManager() {
    }

    private static HashMap<String, String> mInfoMap = new HashMap<>();

    public boolean loadDeviceFromCache() {
        if (MockServices.checkClient()) {
            try {
                String json = MockServices.getClient().getDeviceJson();
                LogManager.getInstance().logInfo("loadDeviceFromCache json = " + json);
                return updateDeviceMap(json);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    private boolean updateDeviceMap(String json) {
        LogManager.getInstance().logError(" updateHookJson json = " + json);
        if (TextUtils.isEmpty(json)) {
            return false;
        }
        try {
            JSONObject jo = new JSONObject(json);
            Iterator<String> keys = jo.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                mInfoMap.put(key, jo.getString(key));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LogManager.getInstance().logError("updateHookJson" + e.getMessage());
            return false;
        }
    }

    public String getDeviceInfo(String key) {
//        LogManager.getInstance().logInfo("getDeviceInfo key = " + key);
        if (mInfoMap.containsKey(key)) {
            return mInfoMap.get(key);
        }
        return "";
    }

    public int getDeviceInfoInt(String key) {
//        LogManager.getInstance().logInfo("getDeviceInfoInt key = " + key);
        if (mInfoMap.containsKey(key)) {
            String value = mInfoMap.get(key);
            try {
                return Integer.parseInt(value);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                return 0;
            }
        }
        return 0;
    }

}
